<script setup lang="ts">
import { ref, onMounted, h } from 'vue';
import { Page } from '@vben/common-ui';
import { NDataTable, NPagination, NButton, NModal, NForm, NFormItem, NInput, useMessage } from 'naive-ui';
import { getChannelList, createChannel, updateChannel, deleteChannel, getChannelDetail, type Channel } from '#/api/model-lake/channels';

const columns = [
  { key: 'id', title: '渠道ID' },
  { key: 'name', title: '渠道名称' },
  { key: 'type', title: '渠道类型' },
  { key: 'base_url', title: '基础URL' },
  { key: 'configs', title: '配置数量', render: (row: any) => (row.configs || []).length },
  { key: 'accounts', title: '账户数量', render: (row: any) => (row.accounts || []).length },
  { key: 'created_at', title: '创建时间' },
  {
    key: 'actions',
    title: '操作',
    render(row: any) {
      return [
        h(NButton, { size: 'small', type: 'primary', onClick: () => handleDetail(row) }, { default: () => '详情' }),
        h(NButton, { size: 'small', type: 'info', class: 'ml-2', onClick: () => handleEdit(row) }, { default: () => '编辑' }),
        h(NButton, { size: 'small', type: 'error', class: 'ml-2', onClick: () => handleDelete(row) }, { default: () => '删除' }),
      ];
    },
  },
];

// 详情表格列定义
const detailColumns = [
  { key: 'field', title: '字段' },
  { key: 'value', title: '值' },
];

const data = ref<Channel[]>([]);
const total = ref(0);
const page = ref(1);
const pageSize = ref(10);
const loading = ref(false);
const message = useMessage();

// 弹窗相关
const showModal = ref(false);
const modalType = ref<'create'|'edit'|'detail'>('create');
const modalTitle = ref('');
const formModel = ref<Channel>({
  name: '',
  type: '',
  base_url: '',
  configs: []
});
const formLoading = ref(false);
const detailData = ref<any[]>([]);

async function fetchData() {
  loading.value = true;
  try {
    const res = await getChannelList({ page: page.value, size: pageSize.value });
    data.value = res.result?.items || [];
    total.value = res.result?.total || 0;
  } catch (error) {
    console.error('获取渠道列表失败:', error);
    message.error('获取渠道列表失败');
    data.value = [];
  } finally {
    loading.value = false;
  }
}

onMounted(fetchData);

function handlePageChange(p: number) {
  page.value = p;
  fetchData();
}

function handlePageSizeChange(s: number) {
  pageSize.value = s;
  page.value = 1;
  fetchData();
}

function handleCreate() {
  modalType.value = 'create';
  modalTitle.value = '新建渠道';
  formModel.value = {
    name: '',
    type: '',
    base_url: '',
    configs: []
  };
  showModal.value = true;
}

function handleEdit(row: Channel) {
  modalType.value = 'edit';
  modalTitle.value = '编辑渠道';
  formModel.value = {
    ...row,
  };
  showModal.value = true;
}

async function handleDetail(row: Channel) {
  modalType.value = 'detail';
  modalTitle.value = '渠道详情';
  formLoading.value = true;
  try {
    const res = await getChannelDetail(row.id!);
    console.log('Detail API Response:', res);

    if (res.result) {
      const channel = res.result;
      formModel.value = {
        id: channel.id,
        name: channel.name,
        type: channel.type,
        base_url: channel.base_url,
        configs: channel.configs,
        accounts: channel.accounts,
        created_at: channel.created_at,
        created_by: channel.created_by,
        updated_at: channel.updated_at,
        updated_by: channel.updated_by,
      };
    } else {
      formModel.value = res.result || {};
    }

    // 转换为表格数据格式
    detailData.value = [
      { field: '渠道ID', value: formModel.value.id || '-' },
      { field: '渠道名称', value: formModel.value.name || '-' },
      { field: '渠道类型', value: formModel.value.type || '-' },
      { field: '基础URL', value: formModel.value.base_url || '-' },
      { field: '配置数量', value: (formModel.value.configs || []).length },
      { field: '账户数量', value: (formModel.value.accounts || []).length },
      { field: '创建时间', value: formModel.value.created_at || '-' },
      { field: '创建者', value: formModel.value.created_by || '-' },
      { field: '更新时间', value: formModel.value.updated_at || '-' },
      { field: '更新者', value: formModel.value.updated_by || '-' },
    ];

    showModal.value = true;
  } catch (error) {
    console.error('获取详情失败:', error);
    message.error('获取详情失败');
  } finally {
    formLoading.value = false;
  }
}

async function handleDelete(row: Channel) {
  if (confirm('确定要删除该渠道吗？')) {
    try {
      await deleteChannel(row.id!);
      message.success('删除成功');
      fetchData();
    } catch (error) {
      console.error('删除失败:', error);
      message.error('删除失败');
    }
  }
}

async function handleModalOk() {
  formLoading.value = true;
  try {
    // 验证必填字段
    if (!formModel.value.name || !formModel.value.type || !formModel.value.base_url) {
      message.error('请填写渠道名称、类型和基础URL');
      return;
    }

    if (modalType.value === 'create') {
      await createChannel(formModel.value);
      message.success('新建成功');
    } else if (modalType.value === 'edit') {
      await updateChannel(formModel.value.id!, formModel.value);
      message.success('编辑成功');
    }
    showModal.value = false;
    fetchData();
  } catch (error) {
    console.error('操作失败:', error);
    message.error(modalType.value === 'create' ? '新建失败' : '编辑失败');
  } finally {
    formLoading.value = false;
  }
}
</script>

<template>
  <Page description="渠道管理" title="渠道管理">
    <div class="mb-4 flex justify-end">
      <NButton type="primary" @click="handleCreate">新建渠道</NButton>
    </div>
    <NDataTable :columns="columns" :data="data" :loading="loading" />
    <div class="mt-4 flex justify-end">
      <NPagination
        v-model:page="page"
        v-model:page-size="pageSize"
        :item-count="total"
        show-size-picker
        :page-sizes="[10, 20, 50, 100]"
        @update:page="handlePageChange"
        @update:page-size="handlePageSizeChange"
      />
    </div>
    <NModal v-model:show="showModal" :title="modalTitle" preset="dialog" :loading="formLoading" :mask-closable="false" :style="{ width: '800px' }">
      <NForm :model="formModel" label-width="100" v-if="modalType !== 'detail'">
        <NFormItem label="渠道名称" path="name">
          <NInput v-model:value="formModel.name" placeholder="请输入渠道名称" />
        </NFormItem>
        <NFormItem label="渠道类型" path="type">
          <NInput v-model:value="formModel.type" placeholder="请输入渠道类型" />
        </NFormItem>
        <NFormItem label="基础URL" path="base_url">
          <NInput v-model:value="formModel.base_url" placeholder="请输入基础URL" />
        </NFormItem>
      </NForm>
      <NDataTable v-else :columns="detailColumns" :data="detailData" :bordered="false" />
      <template #action v-if="modalType !== 'detail'">
        <NButton type="primary" :loading="formLoading" @click="handleModalOk">确定</NButton>
        <NButton class="ml-2" @click="() => (showModal = false)">取消</NButton>
      </template>
      <template #action v-else>
        <NButton @click="() => (showModal = false)">关闭</NButton>
      </template>
    </NModal>
  </Page>
</template>

<style scoped></style>
